<?php
/*******************************************************************
 * [JishiGou] (C)2005 - 2099 Cenwor Inc.
 *
 * This is NOT a freeware, use is subject to license terms
 *
 * @Filename vote.mod.php $
 *
 * @Author http://www.jishigou.net $
 *
 * @Date 2011-05-23 09:39:23 1391268372 2045401099 10230 $
 *******************************************************************/



 

if(!defined('IN_JISHIGOU')) {
    exit('invalid request');
}

class ModuleObject extends MasterObject
{
	
	function ModuleObject($config)
	{
		$this->MasterObject($config);	
		$this->initMemberHandler();
		
				Load::logic('vote');
		$this->VoteLogic = new VoteLogic();
		
		Load::logic('topic');
		$this->TopicLogic = new TopicLogic();
		
		$code = &$this->Code;
		if (empty($code)) {
			$code = 'index';
		}
		
		if (!in_array($code, array('joined', 'daren'))) {
						$this->_check_login();
		}
		
		if (method_exists('ModuleObject', $code)) {
			$this->$code();
		} else {
			exit;
		}
	}

	
	function create()
	{
                if(!($this->MemberHandler->HasPermission($this->Module,$this->Code)))
        {
            json_error($this->MemberHandler->GetError());
        }            	   
	   
		$data = $this->Post;
		
				$member = $this->MemberHandler->MemberFields;
		$data['username'] = jaddslashes($member['username']);
		$data['uid'] = $member['uid'];
		$result = array();
		$ret = $this->VoteLogic->create($data, $result);
		if ($ret > 0) {
			$sys_config = ConfigHandler::get();
			$value = '我发起了一个投票【'.$result['subject'].'】，地址：' . get_full_url($sys_config['site_url'],'index.php?mod=vote&code=view&vid='.$result['vid']);
						$values = array(
				'content' => $value,
				'vid' => $result['vid'],
				'item' => 'vote',
			);
			json_result('发布成功', $values);
		} else {
			if ($ret == -1) {
				json_error("投票主题长度不能小于两个字节。");
			} else if ($ret == -2) {
				json_error("只有一个投票项不允许发布。");
			} else if ($ret == -3) {
				json_error("投票截止时间小于当前时间。");
			}
		}
	}
	
	
	function vote()
	{
	            if(!($this->MemberHandler->HasPermission($this->Module,$this->Code)))
        {
            json_error($this->MemberHandler->GetError());
        }            	   
	   
		$vid = empty($this->Get['vid']) ? 0 : intval($this->Get['vid']);
		$vote = $this->VoteLogic->id2voteinfo($vid);
		$member = $this->MemberHandler->MemberFields;
		if(empty($vote)) {
			json_error('当前投票不存在');
		}
		
				if (TIMESTAMP >= $vote['expiration']) {
			json_error('当前投票已经过期了');
		}
		
				$option = $this->Post['option'];
		if (empty($option)) {
			json_error('你还没有选择呢');	
		}
		
		$param = array(
			'vid' => $vid,
			'uid' => $member['uid'],
			'username' => $member['username'],
			'maxchoice' => $vote['maxchoice'],
			'option' => $option,
			'anonymous' => $this->Post['anonymous'],
		);
		
		$result = array();
		$ret = $this->VoteLogic->do_vote($param, $result);
		switch ($ret) {
			case 1:
				$sys_config = ConfigHandler::get();
				$str_voted = implode('“，”', $result['voted_option']);
				$voted_nums = count($result['voted_option']);
				if ($voted_nums > 1) {
					$str_voted = $str_voted.'”等选项';
				} else {
					$str_voted = $str_voted.'”这1个选项';
				}
				$value = '我参与了投票【'.$vote['subject'].'】　' . get_full_url($sys_config['site_url'],'index.php?mod=vote&code=view&vid='.$vote['vid']) . '投给“'.$str_voted;
				$retval = array(
					'vid' => $vote['vid'],
					'content' => $value,
				);
				json_result('投票成功', $retval);
				break;
			case -1:
				json_error('您已经投过票了，不允许重复投票');	
				break;
			case -2:
				json_error("至多允许选择{$vote['maxchoice']}项目");
				break;
			case -3:
				json_error("投票项不存在");
				break;
		}	
	}
	
		function del()
	{
		$id = empty($this->Post['vid']) ? 0 : intval($this->Post['vid']);
		if ($id) {
			$ret = $this->VoteLogic->delete($id);
		} 
		if (!empty($ret)) {
			json_result('删除投票成功');
		} else {
			json_error('删除投票失败');
		}
	}
	
		function modify_date()
	{
		$vid = empty($this->Post['vid']) ? 0 : intval($this->Post['vid']);
		$expiration = empty($this->Post['expiration']) ? '' : trim($this->Post['expiration']);
		$vote = $this->VoteLogic->id2voteinfo($vid, 'm');
		if (empty($vote)) {
			json_error('当前投票不存在');
		}
		
		if ($vote['uid'] != MEMBER_ID && MEMBER_ROLE_TYPE != 'admin') {
			json_error("你没有权限");
		}
		
		$ret = $this->VoteLogic->modify_expiration($vid, $expiration);
		if ($ret == 1) {
			json_result('修改截止日期成功');
		} else if ($ret == -1){
			json_error('截止时间不能小于当前时间');
		}
	}
	
		function add_opt()
	{
		$vid = empty($this->Post['vid']) ? 0 : intval($this->Post['vid']);
		$option = empty($this->Post['option']) ? '' : trim($this->Post['option']);
		$vote = $this->VoteLogic->id2voteinfo($vid, 'm');
		if (empty($vote)) {
			json_error('当前投票不存在');
		}
		if ($vote['uid'] != MEMBER_ID && MEMBER_ROLE_TYPE != 'admin') {
			json_error('你没有权限');
		}
		$old_options = unserialize($vote['option']);
		$ret = $this->VoteLogic->add_opt($vid, $option);
		if ($ret == 1) {
			json_result('增加投票项成功');
		} else if ($ret == -1){
			json_error('超过了最大的投票项');
		} else if ($ret == -2) {
			json_error('新投票项的长度不符合要求');
		}
	}
	
	
	function vote_publish()
	{
		$max_option = 20;
		$perpage = 5;
		$options = range(1, $perpage);
		$exp_info = $this->VoteLogic->get_publish_form_param();
		extract($exp_info);
		include (template('vote_publish'));	
	}
	
	
	function my_vote()
	{
		$page = empty($this->Get['page']) ? 0 : intval($this->Get['page']);
		$perpage = 8;
		if ($page == 0) {
			$page = 1;
		}
		$start = ($page - 1) * $perpage;
		
		$uid = MEMBER_ID;
		$where_sql = " uid='{$uid}' ";
		$count = DB::result_first("SELECT COUNT(*) FROM ".DB::table('vote')." WHERE {$where_sql} ");
		if ($count) {
			$list = array();
			$sys_config = ConfigHandler::get();
			$query = DB::query("SELECT vid,subject 
								FROM ".DB::table('vote')." 
								WHERE {$where_sql} 
								ORDER BY dateline DESC 
								LIMIT $start,$perpage ");
			while ($value = DB::fetch($query)) {
				$value['vote_url'] = get_full_url($sys_config['site_url'],'index.php?mod=vote&code=view&vid='.$value['vid']);
				$value['radio_value'] = str_replace(array('"', '\''), '', $value['subject']).' - '.$value['vote_url'];
				$list[] = $value;
			}
			$multi = ajax_page($count, $perpage, $page, 'getMyVoteList');
		}
		include(template('vote_list_my_ajax'));
	}
	
	
	function joined()
	{
		$page = empty($this->Get['page']) ? 0 : intval($this->Get['page']);
		$type = trim($this->Get['type']);
		$vid = empty($this->Get['vid']) ? 0 : intval($this->Get['vid']);
		if ($page == 0) {
			$page = 1;
		}
		$prepage = 6;
		$start = ($page - 1) * $prepage;
		$where_sql = " 1 ";
		$page_param = array();
		if ($type == 'follow') {
			$this->_check_login();
			$buddy_ids = $this->_get_buddy(MEMBER_ID);
			$where_sql .= " AND vu.vid='{$vid}' AND uid IN(".jimplode($buddy_ids).") ";
			$page_param = array('c'=>2);
		} else {
			$type = 'all';
			$where_sql .= " AND vu.vid='{$vid}' ";
			$page_param = array('c'=>1);
		}
		$order_sql = " vu.dateline DESC ";
		$count = DB::result_first("SELECT COUNT(*) FROM ".DB::table('vote_user')." AS vu WHERE {$where_sql}");
		if ($count) {
			$query = DB::query("SELECT vu.*,m.nickname  
					   FROM ".DB::table('vote_user')." AS vu 
					   LEFT JOIN ".DB::table("members")." AS m 
					   USING (uid)
					   WHERE $where_sql 
					   ORDER BY $order_sql 
					   LIMIT {$start},{$prepage}");
			while ($value = DB::fetch($query)) {
				$value['option'] = unserialize($value['option']);
				$value['option'] = '"'.implode('","', $value['option']).'"';
				$value['dateline'] = my_date_format2($value['dateline']); 
								if (empty($value['username'])) {
					$value['nickname'] = '**';
				}
				$list[] = $value;
			}
			$multi = ajax_page($count, $prepage, $page, 'getVoteJoined', $page_param);
		}
		include template('vote_ajax_joined');
	}
	
	
	function daren()
	{
		$uids = array();
		$param = array(
			'where' => ' voter_num>0 ',
			'order' => ' voter_num DESC ',
			'limit' => ' 12 ',
		);
		$info = $this->VoteLogic->get_list($param);
		if (!empty($info)) {
			foreach ($info as $val) {
				$uids[] = $val['uid'];
			}
			if (!empty($uids)) {
				$vote_darens = $this->TopicLogic->GetMember($uids);
				include(template('vote_daren_list_ajax'));
			}
		}
		exit;
	}
	
	
	function manage()
	{
		$op = empty($this->Get['op']) ? '' : $this->Get['op'];
		if (empty($op)) {
			exit;
		}
		$vid = empty($this->Get['vid']) ? 0 : intval($this->Get['vid']);
		$vote = $this->VoteLogic->id2voteinfo($vid, 'm');
		if (empty($vote)) {
			json_error('当前投票不存在');
		}
		
		if ($vote['uid'] != MEMBER_ID && MEMBER_ROLE_TYPE != 'admin') {
			json_error("你没有权限");
		}
		
		if ($op == 'modify_date') {
			$exp_info = $this->VoteLogic->get_publish_form_param($vote['expiration']);
			extract($exp_info);
		} else if ($op == 'add_opt') {
			
		}
		include(template('vote_manage'));
	}
	
	
	function _get_buddy($uid)
	{
		$buddyids = array();
		$query = DB::query("SELECT `buddyid`  
							FROM ".DB::table("buddys")." 
							WHERE `uid`='{$uid}'");
		while ($value = DB::fetch($query)) {
			$buddyids[] = $value['buddyid'];
		}
		return $buddyids;
	}
	
	
	function _check_login()
	{
		if (MEMBER_ID < 1) {
			json_error("你需要先登录才能继续本操作");	
		}
	}

}
?>
